import LayerInterface from "./LayerInterface";
import { logInfo } from "../tools/Define";
import EngineHelper from "../../engine/EngineHelper";

export default abstract class LayerManager {

    protected root: any;

    protected list: LayerInterface[]

    protected popFlag: boolean = false;

    protected zOrder: number = 1;

    constructor(zOrder: number = 1, canPop: boolean = true) {
        this.list = []
        this.zOrder = zOrder;
        this.popFlag = canPop;
    }

    init(node: any) {
        this.root = node;
    }

    setZOrder(order: number) {
        this.zOrder = order;
    }

    getZOrder(): number {
        return this.zOrder;
    }

    canPop() {
        return this.popFlag;
    }

    isValid() {
        return EngineHelper.isValid(this.root)
    }

    count() {
        return this.list.length;
    }

    setVisible(flag: boolean) {
        for (let index = 0; index < this.list.length; index++) {
            const element = this.list[index];
            element.setVisible(flag)
        }
    }

    has(layer: LayerInterface) {
        for (let index = 0; index < this.list.length; index++) {
            const element = this.list[index];
            if (layer === element) {
                return true;
            }
        }
        return false;
    }

    //添加layer
    abstract pushView(layer: LayerInterface): void;

    // 移除layer
    abstract popView(view: LayerInterface): boolean;

    //删除指定位置的layer
    removeView(layer: LayerInterface): boolean {
        // logInfo(' LayerManger removeView ')
        for (let index = 0; index < this.list.length; index++) {
            const element: LayerInterface = this.list[index];
            if (layer === element) {
                element.exit();
                this.list.splice(index, 1);
                return true;
            }
        }
        // console.warn(' removeView is not have ', layer, ' list ', this.list)
        return false;
    }

    addView(view: LayerInterface) {
        this.list.push(view)
    }

    clear() {
        // logInfo(' LayerManger clear ')
        for (let index = 0; index < this.list.length; index++) {
            const element: LayerInterface = this.list[index];
            element.exit();
        }
        this.list.length = 0;
    }

    hasView(name: string) {
        for (let index = 0; index < this.list.length; index++) {
            const element = this.list[index];
            if (name == element.getName()) {
                return true;
            }
        }
        return false;
    }
}
